package com.jakewharton.rxbinding2.component;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import io.reactivex.functions.Predicate;
import ohos.agp.components.Component;
import ohos.multimodalinput.event.TouchEvent;

import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread;

final class ComponentTouchObservable extends Observable<TouchEvent> {
  private final Component view;
  private final Predicate<? super TouchEvent> handled;

  ComponentTouchObservable(Component view, Predicate<? super TouchEvent> handled) {
    this.view = view;
    this.handled = handled;
  }

  @Override protected void subscribeActual(Observer<? super TouchEvent> observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(view, handled, observer);
    observer.onSubscribe(listener);
    view.setTouchEventListener(listener);
  }

  static final class Listener extends MainThreadDisposable implements Component.TouchEventListener {
    private final Component view;
    private final Predicate<? super TouchEvent> handled;
    private final Observer<? super TouchEvent> observer;

    Listener(Component view, Predicate<? super TouchEvent> handled,
        Observer<? super TouchEvent> observer) {
      this.view = view;
      this.handled = handled;
      this.observer = observer;
    }
    

    @Override protected void onDispose() {
      view.setTouchEventListener(null);
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
      if (!isDisposed()) {
        try {
          if (handled.test(touchEvent)) {
            observer.onNext(touchEvent);
            return true;
          }
        } catch (Exception e) {
          observer.onError(e);
          dispose();
        }
      }
      return false;
    }
  }
}
